package com.interviewbackend.client;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class ImageAnalysisClient {

    @Value("${qwenvl.api.key}")
    private String apiKey;

    @Value("${qwenvl.model.name}")
    private String imageModelName;

    /**
     * 核心方法：图像+文本分析合并处理（一次多模态会话）
     */
    public String analyzeImageAndText(List<String> imageUrls, String asrText) {
        try {
            // 组装图像内容
            List<Map<String, Object>> contentList = new ArrayList<>();
            for (String url : imageUrls) {
                contentList.add(Collections.singletonMap("image", url));
            }

            // 构造并添加文本提示
            String prompt = String.format(
                    "请根据图片信息和语音识别结果，进行综合分析。图片为面试者连续的表情变化图像。\n" +
                            "请仅输出以下两个方面的简洁分析内容，不得扩展其他信息：\n" +
                            "1）面试者的表情变化反映出哪种主要情绪（如紧张、自信、犹豫等），用一句话精准概括；\n" +
                            "2）语音识别结果中传达的核心观点与重点，用一句话提炼。\n" +
                            "要求：语言简洁清晰，每项不超过三句话。\n\n" +
                            "【语音识别结果】\n%s",
                    asrText
            );
            contentList.add(Collections.singletonMap("text", prompt));


            MultiModalMessage userMessage = MultiModalMessage.builder()
                    .role(Role.USER.getValue())
                    .content(contentList)
                    .build();

            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    .apiKey(apiKey)
                    .model(imageModelName)
                    .message(userMessage)
                    .build();

            MultiModalConversation conversation = new MultiModalConversation();
            MultiModalConversationResult result = conversation.call(param);

            return result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();

        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            log.error("多模态分析失败: {}", e.getMessage(), e);
            return "多模态分析失败：" + e.getMessage();
        }
    }
}
